package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.example.myapplication.utils.QZXTools;
import com.sanstar.baiduFacePay.BaiduFacePay;
import com.sanstar.baiduFacePay.BaiduFacePayCode;
import com.sanstar.baiduFacePay.callback.IBaiduFaceCB;

import java.lang.ref.WeakReference;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: Administrator
 * @date: 2023/7/5
 */

public class CameraTestActivity extends Activity {

    final private String TAG = CameraTestActivity.class.getSimpleName();

    private TextView textView1;
    private TextView textView2;

    SurfaceView mSurface;

    MyHandler mHandler;

    HashMap<String, Object> map = new HashMap<>();

    private class MyHandler extends Handler {

        private WeakReference<Activity> activityWeakReference;

        public MyHandler(Activity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity activity = activityWeakReference.get();
            Log.d(TAG, "msg = " + msg.what);
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        BaiduFacePay.getInstance().setCameraPreview(mSurface, map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                mHandler.sendEmptyMessage(2);
                            }
                        });
                        break;
                    case 2:
                        BaiduFacePay.getInstance().startVerify(map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                String msg = (String) map.get("return_msg");
                                int code = (int) map.get("return_code");
                                Log.d(TAG, "start verity msg = " + msg + ", code = " + code);
                                if(code != -10011 && code != -10012) {
                                    Float rgbScore = (Float) map.get("return_rgbLivenessScore");
                                    Log.d(TAG, "rgbScore = " + rgbScore);
                                    Log.d(TAG, "imagePath = " + map.get("return_imagePath"));
                                }
                                if(msg.equals("SUCC")) {
                                    if(code == 10000) {
                                        runOnUiThread(() -> textView1.setText("相机打开成功"));
                                        Log.d(TAG, "相机打开成功");
                                    } else {
                                        String user_id = (String) map.get("return_user_info_id");
                                        String name = (String) map.get("return_user_info_name");
                                        runOnUiThread(() -> {
                                            textView1.setText("识别成功");
                                            textView2.setText("用户" + user_id + ", 姓名:" + name);
                                        });
                                        Log.d(TAG, "verity user_id = " + user_id + ", name = " + name);
                                        mHandler.sendEmptyMessage(3);
                                    }
                                } else {
                                    runOnUiThread(() -> textView1.setText(msg));
                                }
                            }
                        });
                        break;
                    case 3:
                        BaiduFacePay.getInstance().removeCameraPreview(mSurface, map, new IBaiduFaceCB() {
                            @Override
                            public void response(Map map) {
                                String msg = (String) map.get("return_msg");
                                int code = (int) map.get("return_code");
                                runOnUiThread(() -> textView1.setText(msg));
                                Log.d(TAG, "remove preview msg = " + msg + ", code = " + code);
                                finish();
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        textView1 = findViewById(R.id.Text_tip1);
        textView2 = findViewById(R.id.Text_tip2);
        mSurface = findViewById(R.id.surface_rgb_view);

        mHandler = new MyHandler(this);

//        map.put("pictureURL", "sdcard/123.jpg");
//        BaiduFacePay.getInstance().getFaceFeature(map, new IBaiduFaceCB() {
//            @Override
//            public void response(Map map) {
//                String msg = (String) map.get("return_msg");
//                int code = (int) map.get("return_code");
//                byte[] feature = (byte[]) map.get("feature");
//                Log.d(TAG, "get feature msg = " + msg + ", code = " + code);
//                Log.d(TAG, "feature = " + Base64.getEncoder().encodeToString(feature));
//            }
//        });

        findViewById(R.id.init_verity).setOnClickListener((view) ->{
            BaiduFacePay.getInstance().initBaiduFace(this, map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("初始化" + msg + ", code = " + code));
                    Log.d(TAG, "init msg = " + msg + ", code = " + code);
                }
            });
        });


        findViewById(R.id.preload_env).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().preloadSdkEnv(map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("环境加载" + msg + ", code = " + code));
                    Log.d(TAG, "preload msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.upload_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().manualUpdateFaceData(map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> textView1.setText("内存加载" + msg + ", code = " + code));
                    Log.d(TAG, "upload user msg = " + msg + ", code = " + code + ", user num = " + String.valueOf(info.get("return_user_num")));
                }
            });
        });

        List<Map<String, Object>> mapInfo = new LinkedList<>();

        String str ="WqwAEhxOQRRoNnWY7C/pHdfCSICWHtcFMNyp93AQ84yr+zcxVU8nNXetzjhwQ1g82AMdoMMZw9vyOSUouGpbrTlAyC/JKaDWhP30p3zmzV0NtCBA1IhrRujUxMgTkG4zVNqG8hP3yYtNBDN5+gZ+/J0542FAn4Tlp4vE6Mbx9xNJPISRInIHlWArMhiLt4ycWYeSg0A61IUYHEUIVeKFjE+1ZbA449k19ULvuHDiGT2x0aWgbOkt24Jap6nMqbAsaPqOU/4CyFToB2NYO5GvXALKY8A0CYTFz2zVyKiQzE1jekyPDtbzdnNUw3meAxP90IN7n7ZRrOY990JooHi27M1Tj+8g3qSU3NUqGHsS8pyuRDMBxmYZBJpAP4gjWsCMrVBIsKVKSrRVyRW4CD4HvJDUI6HQ6obb8tQlqNcNhSzJgMUvUWCc1JGW6iefW2Ncouh/wyu9O8SAf9Y3YdxbzMJiOnGlilr0pOFA+fPawgO8ygbgukBt5ZhuW+hnt7Xs2t/OkNZzp5TAolIbLkHsHRsu4wB2ItqEjQLGCKYhtoy8edey+S2mtJfm5To7lkC9/K8uoJE3zqTbN98pPAKQrSiLWa/pIvZVDmRSWMBsMtzPQPvA2njSxBRnvcjXPHzMwFsPcHpb7vX0Gj15TiTmfdqk4GA6Q0ZkQg6y6B708+4=";

        Map map1 = new HashMap() {{
            put("userID", "002999999");
            put("userName", "liuh");
            put("picName", "liuh");
            put("userInfo", "staff");
            put("faceToken", str);
            put("feature", Base64.getDecoder().decode(str));
        }};
        mapInfo.add(map1);



        findViewById(R.id.insert_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().insertFaceDatas(mapInfo, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        Log.d(TAG, "insert user msg = " + msg + ", code = " + code);
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    } else {
                        runOnUiThread(() -> {
                            if(code == 10006) {
                                Log.d(TAG, "用户插入成功 msg = " + msg + ", code = " + code + ", 人数= "+info.get("return_user_num"));
                            }
                            if(code == BaiduFacePayCode.Face_Result_Insert_User_Succ) {
                                textView1.setText("用户插入" + msg + ", 插入人数:" + info.get("return_insert_user_num"));
                                Log.d(TAG, "insert user msg = " + msg + ", code = " + code + ", num = " + info.get("return_insert_user_num"));
                            } else {
                                textView2.setText("当前数据库共有人数:" + info.get("return_user_num"));
                            }
                        });

                    }
                }
            });
        });

        findViewById(R.id.update_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().updateSingleFaceDatas(map1, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    if (info == null) {
                        new RuntimeException("调用返回为空").printStackTrace();
                        return ;
                    }
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    if(msg == null || !msg.equals("SUCC")) {
                        runOnUiThread(() -> textView1.setText(msg));
                        new RuntimeException("调用返回非成功信息：" + msg).printStackTrace();
                    }
                    runOnUiThread(() -> {
                        textView1.setText(map1.get("userName") + "用户更新" + msg);
                        textView2.setText("当前数据库共有人数：" + info.get("return_user_num"));
                    });
                    Log.d(TAG, "update user msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.set_previrew).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().setCameraPreview(mSurface, map, new IBaiduFaceCB() {
                @Override
                public void response(Map info) {
                    String msg = (String) info.get("return_msg");
                    int code = (int) info.get("return_code");
                    runOnUiThread(() -> textView1.setText("预览设置" + msg));
                    Log.d(TAG, "set preview msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.remove_previrew).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().removeCameraPreview(mSurface, map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText(msg));
                    Log.d(TAG, "remove preview msg = " + msg + ", code = " + code);
                }
            });

        });

        findViewById(R.id.start_verity).setOnClickListener((view) -> {
            runOnUiThread(() -> {
                textView1.setText("");
                textView2.setText("");
            });
            BaiduFacePay.getInstance().startVerify(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    Log.d(TAG, "start verity msg = " + msg + ", code = " + code);
                    if(code != -10011 && code != -10012) {
                        Float rgbScore = (Float) map.get("return_rgbLivenessScore");
                        Log.d(TAG, "rgbScore = " + rgbScore);
                    }
                    if(msg.equals("SUCC")) {
                        if(code == 10000) {
                            runOnUiThread(() -> textView1.setText("相机打开成功"));
                            Log.d(TAG, "相机打开成功");
                        } else {
                            String user_id = (String) map.get("return_user_info_id");
                            String name = (String) map.get("return_user_info_name");
                            runOnUiThread(() -> {
                                textView1.setText("识别成功");
                                textView2.setText("用户" + user_id + ", 姓名:" + name);
                            });
                            Log.d(TAG, "verity user_id = " + user_id + ", name = " + name);
                        }
                    } else {
                        runOnUiThread(() -> textView1.setText(msg));
                    }
                }
            });
        });

        findViewById(R.id.stop_verity).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().stopVerify(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("停止识别" + msg));
                    Log.d(TAG, "stop verity msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.get_feature).setOnClickListener((view) -> {
            map.put("pictureURL", "sdcard/345.jpg");
            //Bitmap bitmap = BitmapUtils.getBitmap("sdcard/1.png");
            //byte[] bitmapData = BitmapUtils.bitmapToBytes(bitmap);
            //map.put("bitmapData", bitmapData);
            BaiduFacePay.getInstance().getFaceFeature(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    byte[] feature = (byte[]) map.get("feature");
                    Log.d(TAG, "get feature msg = " + msg + ", code = " + code);
                    Log.d(TAG, "feature = " + Base64.getEncoder().encodeToString(feature));
                }
            });
        });

        findViewById(R.id.del_user).setOnClickListener((view) -> {
            //map.put("userID", "123456789");
            map.put("userName", "liuj");
            BaiduFacePay.getInstance().deleteUser(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("用户liuj删除" + msg));
                    Log.d(TAG, "del user msg = " + msg + ", code = " + code);
                }
            });
        });

        findViewById(R.id.del_all_user).setOnClickListener((view) -> {
            BaiduFacePay.getInstance().deleteAllUser(map, new IBaiduFaceCB() {
                @Override
                public void response(Map map) {
                    String msg = (String) map.get("return_msg");
                    int code = (int) map.get("return_code");
                    runOnUiThread(() -> textView1.setText("所有用户删除" + msg));
                    Log.d(TAG, "del all user msg = " + msg + ", code = " + code);
                }
            });
        });


        findViewById(R.id.release).setOnClickListener((view) -> {
            QZXTools.logD(TAG +"我开始销毁了");
            BaiduFacePay.getInstance().releaseBaiduFace(MyAPP.getInstance());
            QZXTools.logD(TAG +"我销毁完成了");
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaiduFacePay.getInstance().releaseBaiduFace(MyAPP.getInstance());
    }
}